<template>
  <div class="signature-selector">
    <div class="tab_box">
      <div class="tab_item" :class="activeTab==1 ?'active_item':'' " @click="changeType(1)">簽名</div>
      <div class="tab_item" :class="activeTab==2 ?'active_item':'' " @click="changeType(2)">簽章</div>
    </div>

    <div v-if="!showSignaturePad" class="signature-grid">
      <div
        v-for="(sig, index) in activeTypeImgs"
        :key="index"
        class="signature-item"
        :class="{ selected: selectedIndex === index }"
        @click="selectSignature(index)"
      >
        <img :src="sig.ossUrl" alt="signature">
        <i v-if="selectedIndex === index" class="check-icon" />
      </div>

      <div v-if="activeTab == 1" class="signature-item create" @click="createSignature">
        <div class="btn_text">創建簽名</div>
      </div>
      <div v-if="activeTab == 2" class="signature-item create">
        <!-- <div class="btn_text">創建签章</div>
              <uni-file-picker 
                fileMediatype="image" 
                mode="grid" 
                @select="select" 
                @progress="progress" 
                @success="success" 
                @fail="fail" 
              /> -->
              <!-- <uni-file-picker  ref="files" :auto-upload="false" v-show="false"/>
		          <div @click="upload" class="btn_text">創建签章</div> -->
          <uni-file-picker  file-mediatype="all" @select="handleUploadStamp">
            <div class="btn_text">創建签章</div>
          </uni-file-picker>
      </div>
    </div>
    <SignaturePadModal v-show="showSignaturePad" ref="signaturePadRef" :popupVisible.sync="showSignaturePad" />
  </div>
</template>

<script>
import { uploadSignatureImage, getMySignature } from '@/api/signManage/petition.js'
import SignaturePadModal from '../components/SignaturePadModal.vue'
export default {
  components: {
    SignaturePadModal
  },
  name: 'SignatureImage',
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      showSignaturePad: false,
      activeTab: 1,
      selectedIndex: null,
      signatureImgs: [], // 签字图片
      stampImgs: [] // 签章图片
    }
  },
  computed: {
    activeTypeImgs() {
      const arr = this.activeTab === 1 ? this.signatureImgs : this.stampImgs
      return arr.slice(0, 5)
    }
  },
  activated() {
    this.selectedIndex = null
  },
  mounted() {
    getMySignature().then(res => {
      this.signatureImgs = res.data[1]
      this.stampImgs = res.data[2]
    })
  },
  methods: {
    changeType(num) {
      this.activeTab = num
    },
    selectSignature(index) {
      this.selectedIndex = index
      let slectArr = []
      if (this.activeTab === 1) {
        slectArr = this.signatureImgs
      } else {
        slectArr = this.stampImgs
      }
      this.$emit('change', slectArr[index].ossUrl) // 双向数据绑定
      this.$emit('selectImg', slectArr[index].id) // 把选中图片得id传给父组件
    },
    createSignature() {
      this.showSignaturePad = true
      this.$refs.signaturePadRef.open((base64) => {
        this.createSignImg(base64)
      })
    },
    createSignImg(base64Url) {
      uni.showLoading({
        title: '上传中...',
      })
      uploadSignatureImage({ signatureType: this.activeTab, base64String: base64Url }).then(res => {
        const { data } = res
        const imgObj = {
          id: data.id,
          ossUrl: base64Url,
          signatureType: data.signatureType
        }
        if (data.signatureType === 1) {
          this.signatureImgs.unshift(imgObj)
        } else {
          this.stampImgs.unshift(imgObj)
        }
        uni.hideLoading()
        // 創建完成後 默認就選中他
        this.selectSignature(0)
      }).catch(()=>{ uni.hideLoading()})
      
    },
    handleUploadStamp(e){
      const file = e.tempFiles[0]
      this.fileToBase64(file.file).then(base64Url => {
      this.createSignImg(base64Url)
      })
    },
    fileToBase64(file, maxSizeMB = 1) {
      // 判断 file 是否是图片类型
      if (!file.type.startsWith('image/')) {
        uni.showToast({
          title: `請上傳圖片`,
          icon: 'error'
        })
      }
      return new Promise((resolve, reject) => {
        const maxSizeBytes = maxSizeMB * 1024 * 1024

        if (file.size > maxSizeBytes) {
          uni.showToast({
            title: `圖片过大, 圖片大小不能超過 ${maxSizeMB}MB`,
            icon: 'error'
          })
          return
        }

        const reader = new FileReader()

        reader.onload = () => {
          resolve(reader.result) // base64 字符串
        }

        reader.readAsDataURL(file)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.tab_box{
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  padding-bottom: 6px;
  border-bottom: 1px solid #c8c8c8;
  .tab_item{
    padding: 8px 5px;
    cursor: pointer;
     border-bottom: 3px solid transparent;
  }
  .active_item{
    color: #409EFF;
    border-bottom: 3px solid #409EFF;
  }
}
.signature-selector {
  padding: 20px;
}
.signature-grid {
  display: flex;
  gap: 16px 10px;
  padding: 20px;
  flex-wrap: wrap;
  align-items: center;
}
.signature-item {
  border: 2px solid transparent;
  border-radius: 4px;
  padding: 8px;
  text-align: center;
  cursor: pointer;
  position: relative;
  transition: border-color 0.3s;
  display: flex;
  box-sizing: border-box;
  justify-content: center;
  align-items: center;
  width: 30%;
}
.signature-item img {
  border: 2px solid  rgba(0, 0, 0, 0.1);
  width: 100%;
  height: 50px;
  object-fit: contain;
}
.signature-item.selected {
  border-color: #409EFF;
}
.signature-item.create {
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  height : 40%
}
.btn_text {
  /* margin-top: 6px; */
}
.check-icon {
  position: absolute;
  top: 4px;
  right: 4px;
  background: #409EFF;
  color: #fff;
  border-radius: 50%;
  padding: 2px;
}
::v-deep .uni-file-picker__lists{
  display: none;
}
</style>
